package com.example.weather.utils;

import android.os.Handler;
import android.os.Message;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class WeatherUtils {
    public static String data;
    public static int flag = 0;

    public static void getDataFromServer(final Handler handler){
        new Thread(new Runnable() {
            @Override
            public void run() {
                //获取服务器的数据
                String ip = "http://10.0.2.2:8080/weather.json";
                try {
                    URL url =new URL(ip);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    if(con.getResponseCode()==200){
                        InputStream is = con.getInputStream();
                        byte[]buf = new byte[is.available()];
                        is.read(buf);
                        data = new String(buf);
                        //数据取回来了
                        flag = 1;
                        //发一个消息，把数据放消息中去
                        Message msg = new Message();
                        msg.obj = data;
                        //发送消息
                        handler.sendMessage(msg);
                        is.close();
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    /*public static ArrayList<WeatherInfo> getWeatherListFromServer(){
        //getDataFromServer(handler);
        //解析data数据
        while (flag==0){  }
        Gson gson = new Gson();
        Type type = new TypeToken<ArrayList<WeatherInfo>>(){}.getType();
        ArrayList<WeatherInfo> list = gson.fromJson(data,type);
        flag = 0;
        return list;
    }

    public static WeatherInfo getWeather(InputStream is) throws IOException {
        WeatherInfo info = null;
        //读json文件，输入流----文件（关联）
        String data = readJsonFile(is);//json文件的数据读出来，放到String中保存
        //解析数据
        //创建对象
        Gson gson =new Gson();
        info = gson.fromJson(data,WeatherInfo.class);
        //返回对象
        return info;
    }

    private static String readJsonFile(InputStream is) throws IOException {
        //异常产生,捕获处理或抛出异常
        byte[]buf = new byte[is.available()];//输入流大小is.available()
        is.read(buf);
        String data = new String(buf);
        return data;
    }

    public static ArrayList<WeatherInfo> getWeatherList(InputStream is) throws IOException {
        ArrayList<WeatherInfo> lists;
        //读json文件，放入String
        String data = readJsonFile(is);
        //解析
        Gson gson = new Gson();
        Type myType = new TypeToken<ArrayList<WeatherInfo>>(){}.getType();
        lists = gson.fromJson(data,myType);
        return lists;
    }*/
}
